import * as ww from "@wecom/jssdk"
import { getAgentConfigApi, getJsConfigApi, getWorkInfoApi, qyAuthCodeApi, qyLoginApi } from "@/addon/htscrm/api/qywork"
import { removeQyworkToken, setQyworkToken,getQyworkToken } from "./storage"
import { redirect } from "@/utils/common"

function getQuery (name: string) {
  const reg = new RegExp(`(^|&)?` + name + `=([^&]*)(&|$)`, `i`)
  const r = window.location.href.substr(1).match(reg)
  if (r != null) return unescape(r[2])
  return null
}

export async function useCodeAuth(code:string, is_store?:string) {
  const params = {
    code,
    origin: is_store ? 'store': ''
  }
  const res:any = await qyLoginApi(params)
  const { token, ...memberInfo } = res.data
  setQyworkToken(token)
  uni.setStorageSync('qywork_member_info', memberInfo)
  // 如果没有绑定商家，则跳转到绑定页面
  if(memberInfo.is_bind_store == 0) {
    redirect({
      url: '/addon/htscrm/pages/qywork/bind-store',
      param: {
        redirect: encodeURIComponent('/addon/htscrm/pages/qywork/user')
      },
      mode: 'redirectTo'
    })
    return 
  }
  return memberInfo
}
export async function getAuthRedirectUrl(url?:string) {
  const params = {
    url: url ? `${window.location.origin}${url}` : encodeURIComponent(window.location.href),
  }
  const res:any = await qyAuthCodeApi(params)
  location.href = res.data.url
}

export async function qyLogin(url?:string) {
  if(getQyworkToken()) return
  // 开发环境不走登录
  if(process.env.NODE_ENV == 'development') return

  const code = getQuery('code')
  console.log('code', code);
  
  if(code) {
    if(code !== uni.getStorageSync('qywork_code')) {
      uni.setStorageSync('qywork_code', code)
      return await useCodeAuth(code, url)
    } else {
      return uni.getStorageSync('qywork_member_info')
    }
  } else {
    await getAuthRedirectUrl(url)
  }
}

export function qyLogout() {
  removeQyworkToken()
  uni.removeStorageSync('qywork_member_info')
}

/**
 * 注册应用信息。
 */
export async function register() {
  const res:any = await getWorkInfoApi()
  return new Promise((resolve, reject) => {
    ww.register({
      corpId: res.data.corp_id,
      agentId: res.data.agent_id,
      jsApiList: [
        'getCurExternalContact', 
        'sendChatMessage', 
        'getContext', 
        'openUserProfile', 
        'getCurExternalChat', 
        'openExistedChatWithMsg', 
        'navigateToAddCustomer', 
        'sendChatMessage',
        'chooseWXPay'
      ],
      async getConfigSignature(url) {
        const res = await getJsConfigApi({url})
        return res.data
      },
      async getAgentConfigSignature(url) {
        const res = await getAgentConfigApi({url})
        return res.data
      },
      onAgentConfigSuccess() {
        resolve(true)
      },
      onAgentConfigFail() {
        reject(false)
      }
    })
  })
}

/**
 * 获取当前页面的上下文
 */
export function getContext () {
  return ww.getContext()
}

/**
 * 获取当前对话客户微信userId
 */
export function getCurExternalContact () {
  return  ww.getCurExternalContact()
}

/**
 * 发送消息
 */
export function sendChatMessage (param:ww.SendChatMessage) {
  return ww.sendChatMessage(param)
}

/**
 * 打开客户详情
 */
export function openUserProfile (params: { type: ww.OpenUserProfileType, userid: string }) {
  return ww.openUserProfile(params)
}

/**
 * 获取当前群聊ID
 */
export function getCurExternalChat () {
  return ww.getCurExternalChat()
}

/**
 * 打开当前群聊
 */
export function openExistedChatWithMsg (chatId:string) {
  return ww.openExistedChatWithMsg({ chatId })
}
/**
 * 进入添加客户界面
 */
export function navigateToAddCustomer () {
  return ww.navigateToAddCustomer()
}


export function isWeChatWork() {
  return /wxwork/i.test(navigator.userAgent)
}

/** 微信支付 */
export function wxPay(params: ww.WxPayParams) {
  return ww.chooseWXPay(params)
}